package com.study.zgw.messageDemo;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.List;

/**
 * 自定义协议
 * 4 + 1 + 1 + 1 + 4 + 4 = 13
 * 魔数 1 + 版本号 1 + 序列化方式 1 + 指令类型 1 + 请求序号 4 + 数据长度 4
 */
@Slf4j
public class MessageCodec extends ByteToMessageCodec<Message> {
    @Override
    public void encode(ChannelHandlerContext channelHandlerContext, Message msg, ByteBuf out) throws Exception {
        //1 4 字节的魔数
        out.writeBytes(new byte[]{1, 2, 3, 4});
        //2 4 字节的版本号
        out.writeByte(1);
        //3 1 字节的序列化方式 jdk 0 , json 1
        out.writeByte(0);
        //4 1 字节的指令类型
        out.writeByte(msg.getMessageType());
        //5 4 字节的请求序号
        out.writeInt(msg.getSequenceId());
        out.writeByte(0xff);//无意义 填充
        //6 获取内容的字节数组
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(msg);
        byte[] bytes = bos.toByteArray();
        //7 获取内容的长度
        out.writeInt(bytes.length);
        //8 写入内容
        out.writeBytes(bytes);
    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf in, List list) throws Exception {
        int magicNum = in.readInt();
        byte version = in.readByte();
        byte serializerType = in.readByte();
        byte messageType = in.readByte();
        int sequenceId = in.readInt();
        in.readByte();
        int length = in.readInt();
        byte[] bytes = new byte[length];
        in.readBytes(bytes,0,length);
        if (serializerType == 0){
            ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
            Message message = (Message) ois.readObject();
            log.debug("{},{},{},{},{},{}",magicNum,version,serializerType,messageType,sequenceId,length);
            log.debug("{}",message);
            list.add(message);
        }
    }
}
